package cn.yanglq.Rss.core.rssManage;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;

/**
 * Created by yanglq on 2017/6/5.
 */
public class RssUtil {

    private Document doc;

    public String isHtmlOrXml(String url) throws IOException {
        doc = Jsoup.connect(url)

                .data("query", "Java")

                .userAgent("Mozilla")

                .cookie("auth", "token")

                .timeout(6000)

                .get();
// System.out.print(doc.html());
        Elements head = doc.select("rss");
        if (head.size() < 1) {

            Elements rssEl = doc.select("link[type=application/rss+xml]");
            if (rssEl.size() < 1) {
                System.out.println("该地址不支持rss");
                return "eorr";

            } else {
                System.out.println("this a html   RSS地址："
                        + rssEl.get(0).attr("href"));
                return rssEl.get(0).attr("href");
// 如果有多个rss地址 进行遍历
// for(Element e:rssEl){
// System.out.println(e.attr("title")+"----------"+e.attr("href"));
//
// }
            }

        } else {

            return "xml";
        }

// return null;
    }

    public static StringBuilder rssBuild(RssBean rs) {
        StringBuilder sb = new StringBuilder();
        for (RssBean item : rs.getItems()
                ) {
            sb.append(item.getTitle().replaceAll("<[\\s\\S]*?>", "")).append("\n")
                    .append(item.getLink().replaceAll("<[\\s\\S]*?>", "")).append("\n")
                    .append(item.getDate().replaceAll("<[\\s\\S]*?>", "")).append("\n")
                    .append(item.getDescription().replaceAll("<[\\s\\S]*?>", "")).append("\n").append("\n");
        }
        return sb;
    }
}
